package servlet.product.user;

import bean.ProductCart;
import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/productCart.do")
public class productCartServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();

        if (session.getAttribute("cart") == null) {
            session.setAttribute("cart", new ProductCart());
        }
        ProductCart productCart = (ProductCart) session.getAttribute("cart");
        String action = req.getParameter("action");
        if (action == null) {
            resp.sendRedirect("./user/product_cart.jsp");
            return;
        }
        String pid = req.getParameter("pid");
        try {
            Method declaredMethod = productCart.getClass().getDeclaredMethod(action, Integer.class);
            declaredMethod.invoke(productCart, Integer.valueOf(pid));
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        session.setAttribute("cart", productCart);
        if (action.equals("deleteProduct")){
            resp.sendRedirect("./user/product_cart.jsp");
            return;
        }
        resp.sendRedirect("./user/productList.jsp");
    }
}
